package leetcode.dfs;

//617. 合并二叉树
public class MergeTrees {
    public static void main(String[] args) {

    }

    //DFS
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2){
        if(root1==null || root2==null) {
            return root1==null? root2 : root1;
        }
            return dfs(root1,root2);
    }

    //树的前序遍历
    TreeNode dfs(TreeNode r1, TreeNode r2) {
        if (r1==null){
            return r2;
        }
        if (r2==null){
            return r1;
        }
        TreeNode newTree = new TreeNode(r1.val + r2.val);
        newTree.left = dfs(r1.left,r2.left);
        newTree.right= dfs(r1.right,r2.right);
        return newTree;
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}


